<?php
use think\Db;

/**
 * 前台通用化数据输出
 * @param int $status 业务状态码
 * @param string $message 信息提示
 * @param [] $data  数据
 * @return array
 */
function index_json($code, $msg, $data= [], $url = '', $wait = 3) {
    $join = [
        'code' => $code,
        'msg' => $msg,
        'data' => $data,
        'url' => $url,
        'wait' => $wait
    ];
    return json($join);
}

/**
 * 记录日志
 * @param  [type] $uid         [用户id]
 * @param  [type] $username    [用户名]
 * @param  [type] $description [描述]
 * @param  [type] $status      [状态]
 * @return [type]              [description]
 * @return [type] $type        0正确  -1错误日志
 */
function writelog($description,$type=0)
{
    $data['user_name'] = config('nickname') ? config('nickname') : '';
    $data['do_content'] = $description;
    $data['status'] = $type<0 ? -1: 1;
    $data['click_ip'] = request()->ip();
    $data['create_time'] = time();
    $data['os_broswer'] = get_os().'--'.get_broswer();
    
    Db::name('log_home')->insert($data);
}

/**
 * 积分总计
 * @param  [type] $uid         [用户id]
 * @param  [type] $open_id    [用户微信ID]
 */
function integralSum($uid,$open_id)
{
    $map["uid"] = $uid;
    $map["open_id"] = $open_id;
    $map["status"] = 1;
    $map["is_show"] = 1;

    $result = Db::name('credit')->where($map)->sum("branch");

    return $result;
}

/**
 * 剩余积分总计
 * @param  [type] $uid         [用户id]
 * @param  [type] $open_id    [用户微信ID]
 */
function integralSurplus($uid,$open_id)
{

    //*****查询总积分*****//
    $sum = Db::name('credit')->where(["uid"=>$uid,"open_id"=>$open_id,"status"=>1,"is_show"=>1])->sum("branch");

    //*****查询已兑换的积分*****//
    $surplus_sum = Db::name('credit')->where(["uid"=>$uid,"open_id"=>$open_id,"status"=>2,"is_show"=>1])->sum("branch");

    $integral = (int)$sum-(int)$surplus_sum;

    return $integral;
}

/**
 * 二级分销
 * @param  [type] $arr         [用户]
 * @param  [type] $content    [标题内容]
 * @param  [type] $one_price    [一级积分]
 * @param  [type] $two_price    [二级积分]
 */
function distribution($arr=[],$content,$one_price,$two_price)
{
    //*****获取上一级*****//
    $one = grade($arr["pid"]);
    $title = "下级用户".$arr["nickname"].$content."获得".$one_price."积分";
    credit($one["id"],$one["open_id"],1,3,1,$title,$one_price);
    //*****判断是否有上上级*****//
    if($one["pid"] != 0){
        $title = "下级用户".$arr["nickname"].$content."报单获得".$two_price."积分";
        $two = grade($one["pid"]);
        credit($two["id"],$two["open_id"],1,3,1,$title,$two_price);
    }
}